package com.jay.lang.clazz;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileDescriptor;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class SecurityManagerCls {
	// -Djava.security.manager
	public static void main(String[] args) {
		System.out.println(System.getSecurityManager());

		try {
			System.setSecurityManager(new PasswordSecurityManager("123456"));
		} catch (SecurityException se) {
			System.out.println("SecurityManager already set!");
		}
		try (BufferedReader fis = new BufferedReader(
				new FileReader("input.txt"));
				BufferedWriter fos = new BufferedWriter(new FileWriter(
						"output.txt"));) {

			String inputString;
			while ((inputString = fis.readLine()) != null) {
				fos.write(inputString);
				fos.write('\n');
			}
		} catch (IOException ioe) {
			System.out.println("I/O failed for SecurityManagerTest.");
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}

	static class PasswordSecurityManager extends SecurityManager {
		private String password;

		PasswordSecurityManager(String password) {
			super();
			this.password = password;
		}

		private boolean accessOK() {
			BufferedReader dis = new BufferedReader(new InputStreamReader(
					System.in));
			String response;
			System.out.println("What's the secret password?");
			try {
				response = dis.readLine();
				if (response.equals(password))
					return true;
				else
					return false;
			} catch (IOException e) {
				return false;
			}
		}

		@Override
		public void checkRead(FileDescriptor filedescriptor) {
			if (!accessOK())
				throw new SecurityException("Not a Chance!");
		}

		@Override
		public void checkRead(String filename) {
			if (!accessOK())
				throw new SecurityException("No Way!");
		}

		@Override
		public void checkRead(String filename, Object executionContext) {
			if (!accessOK())
				throw new SecurityException("Forget It!");
		}

		@Override
		public void checkWrite(FileDescriptor filedescriptor) {
			if (!accessOK())
				throw new SecurityException("Not!");
		}

		@Override
		public void checkWrite(String filename) {
			if (!accessOK())
				throw new SecurityException("Not Even!");
		}
	}
}
